package me.jiatao.wan.paging3.home

import androidx.paging.PagingSource
import androidx.paging.PagingState
import me.jiatao.wan.data.database.entity.ArticleType
import me.jiatao.wan.data.network.ApiException
import me.jiatao.wan.data.network.HttpConst
import me.jiatao.wan.data.network.api.WanAndroidApi
import me.jiatao.wan.data.network.apiDataCall
import me.jiatao.wan.data.network.pojo.ArticlePojo

/**
 * @Author: taojia
 * @CreateDate: 2021/8/27 4:28 下午
 * @Version: 1.0
 * @Description:
 */

class HomeArticlePagingSource(
    private val api: WanAndroidApi,
    private val articleType: ArticleType,//文章分类
    private val cid: Int = 0//项目/公众号模块的类别标识
) : PagingSource<Int, ArticlePojo>() {
    /** 首页索引 */
    private val startIndex = 0

    override fun getRefreshKey(state: PagingState<Int, ArticlePojo>): Int? {
        return startIndex
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ArticlePojo> {
        val page = params.key ?: startIndex

        return try {
            //主页数据
            val allArticleList = getArticleList(page)

            LoadResult.Page(
                allArticleList,
                if (page <= startIndex) null else page - 1,
                if (allArticleList.isNullOrEmpty()) null else page + 1
            )

        } catch (ex: ApiException) {
            LoadResult.Error(ex)
        }
    }

    /**
     * 根据文章类型获取文章列表
     */
    private suspend fun getArticleList(page: Int): List<ArticlePojo> {
        return when (articleType) {
            ArticleType.HOME ->
                getHomeArticleList(page)
            ArticleType.PROJECT
            -> getProjectArticleList(page)
            ArticleType.WECHAT
            -> getHomeArticleList(page)
        }
    }

    /**
     * 加载首页文章列表
     */
    private suspend fun getHomeArticleList(page: Int): List<ArticlePojo> {
        val allArticleList = ArrayList<ArticlePojo>()

        /** 第一次获取置顶数据 */
        if (page == startIndex) {
            val topArticleList = apiDataCall {
                api.fetchTopArticleListApi()
            }

            allArticleList.addAll(topArticleList.map { item ->
                item.isTop = true
                item
            })
        }

        /** 加载主页数据 */
        val homeArticlePage = apiDataCall {
            api.fetchHomeArticleListApi(page)
        }

        homeArticlePage.articleList?.let {
            allArticleList.addAll(it)
        }

        return allArticleList
    }

    /**
     * 获取项目模块文章列表
     */
    private suspend fun getProjectArticleList(page: Int): List<ArticlePojo> {
        /** 主页数据 */
        val articlePage = apiDataCall {
            api.fetchProjectArticleListApi(page, cid)
        }

        if (articlePage.articleList == null) {
            throw ApiException(HttpConst.CODE_DATA_NULL, "data null")
        } else {
            return articlePage.articleList
        }
    }
}